/**
 * grayrabbit Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package com.grayrabbit.slacker.dababase;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.grayrabbit.slacker.constant.ConfigConstant;

/**
 * mysql数据库实现
 * 
 * @author liyd
 * @version $Id: MySqlProvider.java, v 0.1 2012-5-11 下午12:44:57 liyd Exp $
 */
public class MySqlProvider extends AbstractDatabaseProvider implements DatabaseProvider {

    /**
     * 构造方法
     * 
     * @param driverClassName
     * @param jdbcUrl
     * @param username
     * @param password
     */
    public MySqlProvider() {

        this.driverClassName = ConfigConstant.DRIVER_CLASS_NAME;
        this.jdbcUrl = ConfigConstant.JDBC_URL;
        this.username = ConfigConstant.USERNAME;
        this.password = ConfigConstant.PASSWORD;

    }

    /**
     * 获取数据库表的信息
     * 
     * @param tableName 表名
     * @return List<String[]> 0类型 1列名 2列备注
     */
    public List<String[]> getMetaData(String tableName) {

        List<String[]> list = new ArrayList<String[]>();

        this.createConnection();

        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            //查询时没有数据，只返回表头信息
            pst = connection.prepareStatement("select * from " + tableName + " where 1=2");
            ResultSetMetaData rsd = pst.executeQuery().getMetaData();

            //查询列备注
            pst = connection
                .prepareStatement("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '"
                                  + tableName + "'");
            rs = pst.executeQuery();

            for (int i = 0; i < rsd.getColumnCount(); i++) {

                rs.next();

                String columnClassName = rsd.getColumnClassName(i + 1);

                //如果是sql的date类型，换为util.Date
                if (isSqlDateType(columnClassName)) {

                    columnClassName = "java.util.Date";
                }

                list.add(new String[] { columnClassName, rsd.getColumnName(i + 1),
                        rs.getString("COLUMN_COMMENT") });

            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("can't select table " + tableName);

        } finally {

            try {
                rs.close();
                pst.close();
                pst = null;
                this.closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

}
